﻿namespace GYiwork.Devices.Printer
{
    using Microsoft.VisualBasic;
    using System;
    using System.IO.Ports;
    using System.Linq;
    using System.Net;
    using System.Net.Sockets;
    using System.Runtime.CompilerServices;
    using System.Text;
    using System.Threading;


    public class MI_CIJ_9232
    {
        private SerialPort m_Comm = new SerialPort();
        private Thread m_Job_Thread;
        private string mCIJ_Statue;
        private Socket mClient;
        private byte mDH;
        private byte mDL;
        private string mErrDes = "";
        private string[] mFieldName = new string[10];
        private int mFields = 1;
        private string[] mFieldValue = new string[10];
        private bool mIsExitJob;
        private float mPrintCounts;
        private TransmissionType mProtocolType;
        private bool mUseExternalData;

        public event ErrEventHandler Err;

        public event HostErrEventHandler HostErr;

        public event PrintMessageFinishedEventHandler PrintMessageFinished;

        public void _Close()
        {

            switch (this.mProtocolType)
            {
                case TransmissionType.RS232:
                    this.m_Comm.Close();
                    break;

                case TransmissionType.TCPIP:
                    if (this.mClient.Connected)
                    this.mClient.Close();
                    break;
            }

        }

        public bool _Open(int mComPort, int mBaudrate)
        {
            bool flag = false;
            try
            {
                this.mProtocolType = TransmissionType.RS232;
                this.m_Comm.PortName = "COM" + mComPort.ToString();
                this.m_Comm.BaudRate = mBaudrate;
                this.m_Comm.DataBits = 8;
                this.m_Comm.StopBits = StopBits.One;
                this.m_Comm.ReadBufferSize = 0x400;
                this.m_Comm.WriteBufferSize = 0x400;
                this.m_Comm.Open();
                if (this.m_Comm.IsOpen)
                {
                    return true;
                }
                flag = false;
                this.mErrDes = "端口正在使用..";
            }
            catch (Exception exception)
            {
                flag = false;
                this.mErrDes = string.Format("端口打开异常信息{0}", exception.Message);
            }
            return flag;
        }

        public bool _Open(string mAddr, int mPort)
        {
            bool flag;
            try
            {
                ////建立与服务器连接的套接字                 
                //IPAddress ip = IPAddress.Parse(mAddr);
                //IPEndPoint iep = new IPEndPoint(ip, mPort);
                //mClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //mClient.Connect(iep);

                this.mProtocolType = TransmissionType.TCPIP;
                this.mClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(mAddr), int.Parse(Convert.ToString(mPort)));
                this.mClient.Connect(remoteEP);
                      flag = this.mClient.Connected;
            }
            catch (Exception exception)
            {
                flag = false;
                this.mErrDes = string.Format("连接远程服务终端异常信息{0}", exception.Message);
            }
            return flag;
        }

        public void _StartJob()
        {
            this.mIsExitJob = false;
            this.m_Job_Thread = new Thread(new ThreadStart(this.job));
            this.m_Job_Thread.IsBackground = true;
            this.m_Job_Thread.Start();
        }

        public void _StopJob()
        {
            this.mIsExitJob = true;
            if (this.m_Job_Thread.IsAlive)
            {
                this.m_Job_Thread.Abort();
            }
        }

        private bool Acknowledgement_Printed()
        {
            byte[] buffer = new byte[] { 0x41, 0, 1, 1, 0x41 };
            switch (this.mProtocolType)
            {
                case TransmissionType.RS232:
                    this.m_Comm.DiscardInBuffer();
                    this.m_Comm.Write(buffer, 0, 5);
                    break;

                case TransmissionType.TCPIP:
                    this.SendData(buffer, 5);
                    break;
            }
            if (this.WaitReply() != 0)
            {
                return false;
            }
            return true;
        }

        private byte CheckSum(byte[] CheckData)
        {
            int num = 0;
            for (int i = 0; i <= (CheckData.Length - 1); i++)
            {
                num ^= CheckData[i];
            }
            return (byte) num;
        }

        public bool DeleteJob(int mMessageNo)
        {
            byte[] mBuffer = new byte[20];
            int index = 0;
            mBuffer[index] = 0xc7;
            index++;
            mBuffer[index] = 0;
            index++;
            mBuffer[index] = 2;
            if (mMessageNo > 0x3e7)
            {
                mMessageNo = 0x3e7;
            }
            this.GetLength(mMessageNo);
            mBuffer[index] = this.mDH;
            index++;
            mBuffer[index] = this.mDL;
            index++;
            mBuffer[index] = this.GetChecksum(mBuffer, index);
            index++;
            switch (this.mProtocolType)
            {
                case TransmissionType.RS232:
                    this.m_Comm.DiscardInBuffer();
                    this.m_Comm.Write(mBuffer, 0, index);
                    break;

                case TransmissionType.TCPIP:
                    this.SendData(mBuffer, index);
                    break;
            }
            byte[] buffer2 = this.WaitReport();
            return ((buffer2.Length == 4) && (buffer2[3] == 6));
        }

        public byte GetChecksum(byte[] mBuffer, int mLen)
        {
            int num = 0;
            int num2 = mLen - 1;
            for (int i = 0; i <= num2; i++)
            {
                num = num ^ mBuffer[i];
            }
            return (byte) num;
        }

        private void GetLength(int Din)
        {
            this.mDH = (byte) (Din / 0x100);
            this.mDL = (byte) (Din % 0x100);
        }

        public bool GetReply()
        {
            switch (this.mProtocolType)
            {
                case TransmissionType.RS232:
                    return ((this.m_Comm.BytesToRead > 0) && (this.m_Comm.ReadByte() == 0xe7));

                case TransmissionType.TCPIP:

                    byte[] buffer = this.ReadData();
                    if (buffer[0]==0xe7)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }

                   // return (this.ReadData() == new byte[] { 0xe7 });
            }
            return false;
        }

        public bool Ini()
        {
           this.Acknowledgement_Printed();
           DateTime delaystop = DateTime.Now.AddMilliseconds(500);
           bool isOK = true;
            mClient.Blocking=false;
           while (delaystop > DateTime.Now)
           {
               if (this.WaitReply() == 0)
               {
                   isOK = true;
                   break;
               }
           }
           return isOK;
        }

        private void job()
        {
            do
            {
               // lock (lock1)
                {
                  //  if (!isSend)
                    {
                        if (this.GetReply())
                        {
                            this.mPrintCounts++;
                            this.mCIJ_Statue = "发送数据...";
                            MI_CIJ_9232 mi_cij_ = this;
                            lock (mi_cij_)
                            {
                                PrintMessageFinishedEventHandler printMessageFinished = this.PrintMessageFinished;
                                if (printMessageFinished != null)
                                {
                                    printMessageFinished("0000");
                                }
                            }
                        }
                    }
                }
                Thread.Sleep(5);
            }
            while (!this.mIsExitJob);
        }

        public bool Non_Doubled_Printed(bool m_Enable)
        {
            byte[] buffer = new byte[5];
            buffer[0] = 0xe9;
            buffer[1] = 0;
            buffer[2] = 1;
            if (m_Enable)
            {
                buffer[3] = 1;
            }
            else
            {
                buffer[3] = 0;
            }
            int index = 0;
            do
            {
                buffer[4] = (byte) (buffer[4] ^ buffer[index]);
                index++;
            }
            while (index <= 3);
            switch (this.mProtocolType)
            {
                case TransmissionType.RS232:
                    this.m_Comm.DiscardInBuffer();
                    this.m_Comm.Write(buffer, 0, 5);
                    break;

                case TransmissionType.TCPIP:
                    this.SendData(buffer, 5);
                    break;
            }
            if (this.WaitReply() != 0)
            {
                return false;
            }
            return true;
        }
        object lock1=new object();
       bool isSend=true;

        public bool Print_A_Data()
        {
            lock (lock1)
                {
                isSend = true;
                }
            if (this.mUseExternalData)
            {
                this.SendExteralData();
            }
            return true;
             DateTime delaystop = DateTime.Now.AddMilliseconds(500);
             bool isOK = false;
             while (delaystop > DateTime.Now)
             {
                 if (this.WaitReply() == 0)
                 {
                     isOK= true;
                     break;
                 }
             }
            if (!isOK)
            {
                this.mCIJ_Statue = "发送数据失败";
                ErrEventHandler err = this.Err;
                if (err != null)
                {
                    err("发送数据失败");
                }
            }
            lock (lock1)
            {
                isSend = false;
            }
            return isOK;
           // return false;
        }

        private byte[] ReadData()
        {
            try
            {
              
                long ticks = DateTime.Now.Ticks;
                if (this.mClient.Available > 0)
                {
                    this.mClient.ReceiveTimeout = 100;
                    byte[] buffer = new byte[0x400];
                    int num2 = this.mClient.Receive(buffer, buffer.Length, SocketFlags.Partial);
                    if (num2 > 0)
                    {
                        byte[] buffer2 = new byte[(num2 - 1) + 1];
                        int num3 = num2 - 1;
                        for (int i = 0; i <= num3; i++)
                        {
                            buffer2[i] = buffer[i];
                        }
                        return buffer2;
                    }
                    return new byte[] { 0x15 };
                }
                if ((DateTime.Now.Ticks - ticks) > 0x989680)
                {
                    this.ErrDes = "通讯超时....";
                    return new byte[] { 0x16 };
                }
                Thread.Sleep(1);
            }
            catch (SocketException exception)
            {
                HostErrEventHandler hostErr = this.HostErr;
                if (hostErr != null)
                {
                    hostErr(exception.Message);
                }
                this.mErrDes = exception.Message;
            }
            return new byte[1];
        }

        public bool SelectJobByName(string MessageName)
        {
            byte[] mBuffer = new byte[20];
            int index = 0;
            mBuffer[index] = 160;
            index++;
            this.GetLength(MessageName.Length);
            mBuffer[index] = this.mDH;
            index++;
            mBuffer[index] = this.mDL;
            index++;
            int num2 = MessageName.Length - 1;
            for (int i = 0; i <= num2; i++)
            {
                char ch = MessageName[i];
                byte[] bytes = Encoding.Default.GetBytes(ch.ToString());
                mBuffer[index] = bytes[0];
                index++;
            }
            mBuffer[index] = this.GetChecksum(mBuffer, index);
            index++;
            switch (this.mProtocolType)
            {
                case TransmissionType.RS232:
                    this.m_Comm.DiscardInBuffer();
                    this.m_Comm.Write(mBuffer, 0, index);
                    break;

                case TransmissionType.TCPIP:
                    this.SendData(mBuffer, index);
                    break;
            }
            byte[] buffer3 = this.WaitReport();
            return ((buffer3.Length == 4) && (buffer3[3] == 0));
        }

        public bool SelectJobByNum(int mMessageNo)
        {
            byte[] mBuffer = new byte[20];
            int index = 0;
            mBuffer[index] = 0x98;
            index++;
            mBuffer[index] = 0;
            index++;
            mBuffer[index] = 2;
            index++;
            if (mMessageNo > 0x3e7)
            {
                mMessageNo = 0x3e7;
            }
            this.GetLength(mMessageNo);
            mBuffer[index] = this.mDH;
            index++;
            mBuffer[index] = this.mDL;
            index++;
            mBuffer[index] = this.GetChecksum(mBuffer, index);
            index++;
            switch (this.mProtocolType)
            {
                case TransmissionType.RS232:
                    this.m_Comm.DiscardInBuffer();
                    this.m_Comm.Write(mBuffer, 0, index);
                    break;

                case TransmissionType.TCPIP:
                    this.SendData(mBuffer, index);
                    break;
            }
            if (this.WaitReply() != 0)
            {
                return false;
            }
            return true;
        }

        private bool SendData(byte[] mBuffer, int mSize)
        {
            byte[] buffer = new byte[mSize];
            int num = mSize - 1;
            for (int i = 0; i <= num; i++)
            {
                buffer[i] = mBuffer[i];
            }
            try
            {
                this.mClient.Send(buffer, buffer.Length, SocketFlags.Partial);
                return true;
            }
            catch (Exception exception)
            {
                this.mErrDes = exception.Message;
                return false;
            }
        }

        private void SendExteralData()
        {
            byte[] mBuffer = new byte[0x3e9];
            int index = 0;
            mBuffer[0] = 0xe8;
            index = 1;
            mBuffer[1] = 0;
            index = 2;
            mBuffer[2] = 0x24;
            index = 3;
            int num2 = this.mFields - 1;
            for (int i = 0; i <= num2; i++)
            {
                //mBuffer[index] = 0x12;
                //index++;

              //  mBuffer[index] = 0x01;

                int Varnum = i + 1;
                mBuffer[index] = Convert.ToByte(Varnum % 0x100);//0x01;
                index++;
                this.GetLength(this.mFieldValue[i].Length);
                mBuffer[index] = this.mDH;
                index++;
                mBuffer[index] = this.mDL;
                index++;

                byte[] byteArray = Encoding.UTF8.GetBytes(this.mFieldValue[i]);

                int num4 = this.mFieldValue[i].Length;
                for (int j = 0; j< byteArray.Length; j++)
                {
                    mBuffer[index] = byteArray[j];
                    index++;
                }
                //mBuffer[index] = 0x01;
                //index++;
                //mBuffer[index] = this.mDH;
                //index++;
                //mBuffer[index] = this.mDL;
                //index++;

                //mBuffer[index] = 0x12;
                //index++;
            }
            this.GetLength(index - 3);
            mBuffer[1] = this.mDH;
            mBuffer[2] = this.mDL;
            mBuffer[index] = this.GetChecksum(mBuffer, index);
            switch (this.mProtocolType)
            {
                case TransmissionType.RS232:
                    this.m_Comm.Write(mBuffer, 0, index + 1);
                    break;

                case TransmissionType.TCPIP:
                    this.SendData(mBuffer, index + 1);
                    break;
            }
        }

        public bool Start_Jet()
        {
            byte[] mBuffer = new byte[5];
            int index = 0;
            mBuffer[index] = 0xc6;
            index++;
            mBuffer[index] = 0;
            index++;
            mBuffer[index] = 1;
            index++;
            mBuffer[index] = 1;
            index++;
            mBuffer[index] = this.GetChecksum(mBuffer, index);
            index++;
            switch (this.mProtocolType)
            {
                case TransmissionType.RS232:
                    this.m_Comm.DiscardInBuffer();
                    this.m_Comm.Write(mBuffer, 0, index);
                    break;

                case TransmissionType.TCPIP:
                    this.SendData(mBuffer, index);
                    break;
            }
            if (this.WaitReply() != 0)
            {
                return false;
            }
            return true;
        }

        public bool Start_Printer()
        {
            byte[] mBuffer = new byte[5];
            int index = 0;
            mBuffer[index] = 0x30;
            index++;
            mBuffer[index] = 0;
            index++;
            mBuffer[index] = 1;
            index++;
            mBuffer[index] = 0xff;
            index++;
            mBuffer[index] = this.GetChecksum(mBuffer, index);
            index++;
            switch (this.mProtocolType)
            {
                case TransmissionType.RS232:
                    this.m_Comm.DiscardInBuffer();
                    this.m_Comm.Write(mBuffer, 0, index);
                    break;

                case TransmissionType.TCPIP:
                    this.SendData(mBuffer, index);
                    break;
            }
            if (this.WaitReply() != 0)
            {
                return false;
            }
            return true;
        }

        public bool Stop_Jet()
        {
            byte[] mBuffer = new byte[5];
            int index = 0;
            mBuffer[index] = 0xc6;
            index++;
            mBuffer[index] = 0;
            index++;
            mBuffer[index] = 1;
            index++;
            mBuffer[index] = 0;
            index++;
            mBuffer[index] = this.GetChecksum(mBuffer, index);
            index++;
            switch (this.mProtocolType)
            {
                case TransmissionType.RS232:
                    this.m_Comm.DiscardInBuffer();
                    this.m_Comm.Write(mBuffer, 0, index);
                    break;

                case TransmissionType.TCPIP:
                    this.SendData(mBuffer, index);
                    break;
            }
            if (this.WaitReply() != 0)
            {
                return false;
            }
            return true;
        }

        public bool Stop_Printer()
        {
            byte[] mBuffer = new byte[5];
            int index = 0;
            mBuffer[index] = 0x30;
            index++;
            mBuffer[index] = 0;
            index++;
            mBuffer[index] = 1;
            index++;
            mBuffer[index] = 1;
            index++;
            mBuffer[index] = this.GetChecksum(mBuffer, index);
            index++;
            switch (this.mProtocolType)
            {
                case TransmissionType.RS232:
                    this.m_Comm.DiscardInBuffer();
                    this.m_Comm.Write(mBuffer, 0, index);
                    break;

                case TransmissionType.TCPIP:
                    this.SendData(mBuffer, index);
                    break;
            }
            if (this.WaitReply() != 0)
            {
                return false;
            }
            return true;
        }

        public int WaitReply()
        {
            switch (this.mProtocolType)
            {
                case TransmissionType.RS232:
                {

                    return -1;
                }
                case TransmissionType.TCPIP:
                {
                    byte[] buffer2 = this.ReadData();

                        byte Fin = 0x06;

                        if (buffer2.Length > 0 && buffer2.Contains(Fin))
                        {
                            return 0;
                        }

                    return -1;
                }
            }
            return -1;
        }

        public byte[] WaitReport()
        {
            float timer;
            bool flag;
            switch (this.mProtocolType)
            {
                case TransmissionType.RS232:
                  //  timer = (float) DateAndTime.Timer;
                    goto Label_00BB;

                case TransmissionType.TCPIP:
                    return this.ReadData();

                default:
                    return new byte[1];
            }
        Label_00BB:
            return new byte[] { 0x15 };
        }

        public string CIJ_Statue
        {
            get
            {
                return this.mCIJ_Statue;
            }
            set
            {
                this.mCIJ_Statue = value;
            }
        }

        public string ErrDes
        {
            get
            {
                return this.mErrDes;
            }
            set
            {
                this.mErrDes = value;
            }
        }

        public string[] FieldName
        {
            get
            {
                return this.mFieldName;
            }
            set
            {
                this.mFieldName = value;
            }
        }

        public int Fields
        {
            get
            {
                return this.mFields;
            }
            set
            {
                this.mFields = value;
            }
        }

        public string[] FieldValue
        {
            get
            {
                return this.mFieldValue;
            }
            set
            {
                this.mFieldValue = value;
            }
        }

        public bool UseExternalData
        {
            get
            {
                return this.mUseExternalData;
            }
            set
            {
                this.mUseExternalData = value;
            }
        }

        public delegate void ErrEventHandler(string Description);

        public delegate void HostErrEventHandler(string Description);

        public delegate void PrintMessageFinishedEventHandler(string PrintMessage);

        private enum TransmissionType
        {
            RS232,
            TCPIP
        }
    }
}

